package com.erp.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.Utils.DateFormat;
import com.erp.Utils.ResponseModel;
import com.erp.entity.Demand;
import com.erp.entity.Label;
import com.erp.entity.Project;
import com.erp.enums.statusCode;
import com.erp.security.dto.JwtUserDto;
import com.erp.service.DemandService;
import com.erp.service.LabelService;
import com.erp.service.ProjectService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 需求录入表 前端控制器
 * </p>
 *
 * @author  张彬 
 * @since 2021-10-14
 */
@RestController
@RequestMapping("/demand")
public class DemandController {
    @Resource
    ProjectService projectService;
    @Resource
    LabelService labelService;
    @Resource
    DemandService demandService;

    //抽象出来公用
    public ModelAndView getProjectName(){
        ModelAndView modelAndView = new ModelAndView();
        List<Project> projectList = projectService.list(new QueryWrapper<Project>()
                .eq("status",statusCode.Default.getValue()).select("id", "project_name"));
        modelAndView.addObject("listProject", projectList);
        return modelAndView;

    }

    //展示页面
    @RequestMapping("listView")
    @PreAuthorize("hasAnyAuthority('demand:list')")
    public ModelAndView listView() {
        ModelAndView modelAndView = getProjectName();
        modelAndView.setViewName("system/demand/demand_list");
        return modelAndView;
    }

    // 获取标签信息
    @RequestMapping(value = "getLabelData", method = RequestMethod.GET)
    @ResponseBody
    public ResponseModel getLabelData() {
        List<Label> labelList = labelService.list( new QueryWrapper<Label>().eq("status",statusCode.Default.getValue()));
        return ResponseModel.success(labelList);
    }

    // 保存需求数据
    @PostMapping("saveDemandData")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('demand:add')")
    public ResponseModel saveDemandData(@RequestBody Map<String, String> map) {
        Demand demand = new Demand();
        demand.setProjectName(map.get("project"));
        demand.setDemandTime(map.get("date"));
        demand.setCreateTime(DateFormat.getTime());
        demand.setVersionId(map.get("version"));
        demand.setDemandInfo(map.get("context"));
        demand.setLabelName(map.get("label_name"));
        demand.setDemandStatus(Convert.toInt(map.get("demandStatus")));
        demand.setDelStatus(statusCode.Default.getValue());//逻辑删除
        String sumMonth = Convert.toStr(DateUtil.parse(map.get("date")).year()) +"-" + Convert.toStr(DateUtil.parse(map.get("date")).month()+1);
        demand.setSumMonth(sumMonth);
        // 获取当前登录的用户名
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = jwtUserDto.getMyUser().getUserName();
        demand.setCreateName(userName);
        boolean status = demandService.save(demand);
        //往项目表里存储需求时间和需求标签，方面后面页面渲染
        saveRedundancyData(map.get("project"));
        if (status) {
            return ResponseModel.success("需求录入成功");
        } else {
            return ResponseModel.fail("需求录入失败");
        }
    }
    // 此函数是为了方便主界面1页面数据展示用的，有效缓解频繁取数据库数据
    public void saveRedundancyData(String projectName) {
        List<Demand> demandList = demandService.list(new QueryWrapper<Demand>().eq("projectName", projectName).select("id","label_name", "sum_month"));
        List<String> list = new ArrayList<>();
        List<String> monthList = new ArrayList<>();
        for (Demand demand : demandList) {
            //先取出标签名称 逐个遍历插入
            for (String name : Convert.toStrArray(demand.getLabelName())) {
                if (!list.contains(name)) {
                    list.add(name);
                }
            }
            //取出插入月份名称 逐个遍历插入
            if (!monthList.contains(demand.getSumMonth())) {
                monthList.add(demand.getSumMonth());

            }
        }
        String joinLabelName = Convert.toStr(list);
        String joinMonch = Convert.toStr(monthList);
        Project project = new Project();
        project.setSumDemandTime(joinMonch);
        project.setSumDemandLabel(joinLabelName);
        UpdateWrapper<Project> projectUpdateWrapper = new UpdateWrapper<>();
        projectUpdateWrapper.eq("project_name", projectName);
        //第一个参数是实体对象，第二个是条件构造
        projectService.update(project, projectUpdateWrapper);
    }

    // 列表数据
    @RequestMapping(value = "/getListData", method = RequestMethod.GET)
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('demand:list')")
    public Map<String, Object> getListData(
            @RequestParam(value = "page") int page,
            @RequestParam(value = "limit") int limit) {
        IPage<Demand> demandPage = new Page<>(page, limit);//参数一是当前页，参数二是每页个数
        demandPage = demandService.page(demandPage, new QueryWrapper<Demand>().eq("del_status",statusCode.Default.getValue())
                .orderByDesc("create_time"));
        List<Demand> demandList = demandPage.getRecords();//获取数据，这里面还有当前页码数还有总数据参数
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", demandPage.getTotal());
        map.put("data", demandList);
        return map;
    }

    // 修改需求数据
    @PostMapping("editView")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('demand:edit')")
    public ResponseModel editView(@RequestBody JSONObject data) {
        Demand demand = new Demand();
        demand.setId(data.getInt("demandId"));
        demand.setProjectName(data.getStr("project"));
        demand.setDemandTime(data.getStr("date"));
        demand.setLabelName(data.getStr("label_name"));
        demand.setDemandInfo(data.getStr("context"));
        demand.setVersionId(data.getStr("version"));
        demand.setDemandStatus(data.getInt("demandStatus"));
        boolean status = demandService.updateById(demand);
        if (status) {
            return ResponseModel.success("修改成功");
        } else {
            return ResponseModel.fail("修改失败");
        }
    }
    //修改页面
    @GetMapping("editView")
    @PreAuthorize("hasAnyAuthority('demand:edit')")
    public ModelAndView editView(@RequestParam int id) {
        ModelAndView modelAndView = new ModelAndView();
        //获取指定的需求信息
        Map<String,Object> map = demandService.getMap(new QueryWrapper<Demand>().eq("id",id));
        modelAndView.addObject("demand",map);
        // 获取所有的项目名称
        List<Map<String,Object>> projectList = projectService.listMaps(new QueryWrapper<Project>()
                .select("id", "project_name"));

//        for (Map<String,Object> project : projectList){
//            if (project.get("project_name").equals(map.get("projectName"))){
//                project.put("select","selected");
//            }
//        }
        modelAndView.addObject("listProject", projectList);
        // 下拉框默认选中判断用的
        modelAndView.addObject("projectName",map.get("projectName"));
        modelAndView.addObject("demand_status",map.get("demand_status"));
//        ModelAndView modelAndView = getProjectName();
        modelAndView.setViewName("system/demand/demand_edit");
        return modelAndView;
    }
    //修改页面穿梭框
    // 获取标签信息
    @RequestMapping(value = "getLabel", method = RequestMethod.GET)
    @ResponseBody
    public ResponseModel getLabel(@RequestParam int demandId) {
         List<Map<String,Object>> labelList = labelService.listMaps(null);
        Demand demand = demandService.getById(demandId);
        //存储已选中的id
        List<Object> checkIds = new  ArrayList<>();
        //已选中的
        String[] checkLabel = Convert.toStrArray(demand.getLabelName());
        for (Map<String,Object> label:labelList){
            if (Arrays.asList(checkLabel).contains(Convert.toStr(label.get("label_name")))){
                label.put("checked","true");
                checkIds.add(label.get("id"));
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("labelList",labelList);
        map.put("checkIds",checkIds);
        return ResponseModel.success(map);
    }
}
